﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace DNA.Mvc.jQuery
{


    public abstract class RemoteDataBindableContainer<TModel, TComponentItem> : DataBindableContainer<TModel, TComponentItem>
        where TComponentItem : ViewComponent
        where TModel : class
    {
        private HtmlTemplate clientItemTemplate = new HtmlTemplate();

        public bool HasItems
        {
            get { return InnerItems.Count > 0; }
        }

        internal IList<TComponentItem> GetItems() { return InnerItems; }

        internal void ClearItems() { InnerItems.Clear(); }

        /// <summary>
        /// Gets/Sets the client template (jQuery tmpl)
        /// </summary>
        public HtmlTemplate ClientItemTemplate
        {
            get { return clientItemTemplate; }
            set { clientItemTemplate = value; }
        }

        /// <summary>
        /// Gets/Sets the remote data source url.
        /// </summary>
        public string RemoteDataSource { get; set; }

        private string httpMethod = "GET";

        /// <summary>
        /// Gets/Sets the httpmethod use in ajax request.Default is "GET".
        /// </summary>
        public string HttpMethod
        {
            get { return httpMethod; }
            set { httpMethod = value; }
        }

        /// <summary>
        /// Render the jQueryTemplate to context output.
        /// </summary>
        /// <param name="writer"></param>
        protected void RenderjQueryTemplate(HtmlTextWriter writer)
        {
            writer.WriteBeginTag("script");
            writer.WriteAttribute("id", this.Id + "_tmpl");
            writer.WriteAttribute("type", "text/x-jquery-tmpl");
            writer.Write(HtmlTextWriter.TagRightChar);
            ClientItemTemplate.WriteTo(writer);
            writer.WriteEndTag("script");
        }

        public override void RenderContent(HtmlTextWriter writer)
        {
            if (string.IsNullOrEmpty(RemoteDataSource) && InnerItems.Count > 0)
                base.RenderContent(writer);
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
            base.RenderEndTag(writer);
            if (!ClientItemTemplate.IsEmpty)
                RenderjQueryTemplate(writer);
        }
    }
}
